<template>
  <div id="chat">
    <el-container class="chat-page">
      <el-aside width="280px" class="chat-list-box">
        <div class="chat-list-header">
          <el-input class="search-text" placeholder="搜索" v-model="searchText">
            <i class="el-icon-search el-input__icon" slot="prefix"> </i>
          </el-input>
          <el-button plain class="add-btn" icon="el-icon-plus" title="添加好友" @click="onShowAddFriend()"></el-button>
          <add-friend :dialogVisible.sync="showAddFriend"></add-friend>
        </div>
        <div class="chat-list-loading" v-if="loading" v-loading="true" element-loading-text="消息接收中..."
          element-loading-spinner="el-icon-loading" element-loading-background="#eee">
          <div class="chat-loading-box"></div>
        </div>
        <el-scrollbar class="chat-list-items">
          <div v-for="(chat, index) in chatsList" :key="index">
            <!-- 如果 showName 包含 searchText，则显示该聊天项 -->
            <chat-item :chat="chat" :index="index" :content="chatCont(chat)" :num="num"
              @click.native="onActiveItem(index)" />
          </div>
        </el-scrollbar>
      </el-aside>
      <el-container class="chat-box">

        <!-- <chat-box v-if="chatStore.activeChat[index]" :chat="mergeChat(index)"></chat-box> -->
        <chat-box v-if="activeChatList" @add-chat="updateActiveChatList" :chatsList="chatsList[this.index]"
          :activeChatList="activeChatList"></chat-box>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import ChatItem from "@/components/chat/ChatItem.vue";
import ChatBox from "@/components/chat/ChatBox.vue";
import AddFriend from "@/components/AddFriend.vue";
import indexedDB from '@/services/indexdDB';
export default {
  name: 'ChatView',
  components: { ChatItem, ChatBox, AddFriend },
  data () {
    return {
      // loading:true,
      num: 0,
      showAddFriend: false,
      token: '',
      index: "",
      searchText: '', // 模拟搜索文本，可以根据实际需求更改
      // chatsList: [],//聊天列表
      activeChatList: '',//聊天详情

    }
  },
  // watch: {
  //   // 监听 chatsList 的变化
  //   'chatsList': function (newChatsList) {
  //     // 确保 chatsList 是有效且新的列表存在
  //     if (Array.isArray(newChatsList) && newChatsList.length > 0) {
  //       // 确保 index 有效
  //       if (this.index >= 0 && this.index < newChatsList.length) {
  //         const chatItem = newChatsList[this.index];

  //         // 如果 chatItem 和其数据有效，更新 activeChatList
  //         if (chatItem && chatItem.chatData && Array.isArray(chatItem.chatData.list)) {
  //           this.activeChatList = chatItem.chatData.list;
  //         }
  //       }
  //     }
  //   }
  // },
  watch: {
  // 监听 chatsList 的变化
  'chatsList': function (newChatsList) {
    // 首先检查 newChatsList 是否有效且 index 在有效范围内
    if (Array.isArray(newChatsList) && newChatsList.length > 0 && this.index >= 0 && this.index < newChatsList.length) {
      const chatItem = newChatsList[this.index];
      
      // 确保 chatItem 存在且具有 chatData 属性
      if (chatItem && chatItem.chatData && Array.isArray(chatItem.chatData.list)) {
        this.activeChatList = chatItem.chatData.list;
      }
    }
  }
  },
  computed: {
    chatsList () {
      return this.$store.getters['chatsList'];
    },
    loading () {
      return this.$store.getters['loading'];
    },
    // 根据搜索文本动态过滤聊天列表
    chatCont () {
      // 计算并返回最后一条消息的 content
      // const lastMessage = this.chat.chatData.list[this.chat.chatData.list.length - 1];
      // return lastMessage ? lastMessage.content : '';
      return (chat) => {
        const lastMessage = chat?.chatData?.list?.[chat.chatData.list.length - 1];
        return lastMessage ? lastMessage.content : '';
      };
    },
  },

  created () {
    //  const token = sessionStorage.getItem('token')

    // 交流记录
    // this.webInit(token)
    // this.fetchChatMessages(this.token)


    // websocket

  },
  async mounted () {

    // await this.fetchItems(); // 页面加载时获取所有 items
    // this.webInit(this.token)
  },
  methods: {    // 自动滚动到聊天框底部

    // 处理子组件传递的事件，并更新 activeChatList
    // async addItem () {
    //   if (!this.newItem.name) return;
    //   await indexedDB.addItem(this.newItem);
    //   this.newItem = { id: Date.now(), name: '' }; // 重置表单
    //   this.fetchItems(); // 重新加载数据
    // },
    // async fetchItems () {
    //   this.items = await indexedDB.getAllItems();
    // },
    // async deleteItem (id) {
    //   await indexedDB.deleteItem(id);
    //   this.fetchItems(); // 删除后重新加载数据
    // },

    // 添加新的聊天到 activeChatList
    async updateActiveChatList (newChat) {
      console.log(newChat, "newChat");
      // console.log(this.activeChatList, " this.activeChatList", this.chatsList[this.index]);

      this.activeChatList.push(newChat);
      // 更新数据库
      await indexedDB.addItem(this.chatsList[this.index]);
    },
    // 查询所有聊天记录 
    // async fetchChatMessages (e) {
    //   try {
    //     const data = await this.$http.post('/chat/session/list', { token: e })
    //     // console.log(data);
    //     this.chatsList = data.data
    //     // const data = await this.$http.post('/chat/record/list', { token: this.token, chatSessionId: this.chatsList[index].chatSessionId, startId: 0, limit: 100, direction: "down" })
    //     // 提取所有 chatSessionId
    //     const chatSessionIds = data.data.map(item => item.chatSessionId);


    //     for (let i = 0; i < chatSessionIds.length; i++) {
    //       const chatSessionId = chatSessionIds[i]
    //       try {
    //         const data1 = await this.$http.post('/chat/record/list', { token: this.token, chatSessionId, startId: 0, limit: 100, direction: "down" })
    //         // console.log(data1.data.list);
    //         // 将获取到的数据放入 chatlist 中
    //         const chatItem = this.chatsList.find(c => c.chatSessionId === chatSessionId);
    //         if (chatItem) {
    //           chatItem.chatData = data1.data; // 可以根据需要修改字段名
    //         }
    //       } catch (error) {
    //         console.log(`获取 chatSessionId ${chatSessionId} 的记录时发生错误:`, error);

    //       }

    //     }
    //     console.log("chatsList", this.chatsList);
    //     this.loading = false
    //     // 上传数据库
    //     this.additem()
    //   } catch (error) {
    //     console.log("获取聊天会话列表时发生错误:", error);

    //   }
    // },
    // 传入数据库
    async additem () {
      try {
        // 判断 chatsList 是否为空
        if (!this.chatsList || this.chatsList.length === 0) {
          console.log("No data to upload.");
          return;
        }

        // 使用批量上传的方式遍历 chatsList 数组，将每一项上传到数据库
        for (let chatItem of this.chatsList) {
          // 假设我们将每个 chatItem 通过 indexedDB.addItem 添加到数据库
          await indexedDB.addItem(chatItem); // 假设 `indexedDB.addItem` 是一个返回 Promise 的方法

        }
        // 上传完后，你可能需要做一些操作，比如刷新 UI 或重置表单等
        // 可以考虑调用方法来刷新数据，例如：
        // this.fetchItems(); // 重新加载数据

      } catch (error) {
        // 捕获并输出上传时的错误
        console.error("Error uploading chats to the database:", error);
      }
    },
    // 加载数据
    // async fetchItems () {
    //   this.chatsList = await indexedDB.getAllItems();
    // },


    // 激活聊天项
    async onActiveItem (index) {
      this.index = index
      console.log(this.activeChatList);
      // 确保索引在范围内
      if (this.index >= 0 && this.index < this.chatsList.length) {
        this.activeChatList = this.chatsList[index].chatData.list
      }
    },
    // 删除聊天项
    onDelItem (index) {
      this.chatStore.chats.splice(index, 1);
    },
    // 设置置顶聊天项
    onTop (index) {
      const chat = this.chatStore.chats.splice(index, 1)[0];
      this.chatStore.chats.unshift(chat);
    },

    onShowAddFriend () {
      this.showAddFriend = true;
      // console.log(this.showAddFriend);

    }
  }
}
</script>

<style lang="scss" scoped>
#chat {
  width: 100%;
}

::v-deep.el-input {
  width: 82%;
}

.chat-page {
  height: 100%;

  .chat-list-box {
    display: flex;
    flex-direction: column;
    border-right: #53a0e79c solid 1px;
    background: white;
    width: 3rem;

    .chat-list-header {
      padding: 3px 8px;
      line-height: 50px;
      border-bottom: 1px #ddd solid;
      display: flex;
      justify-content: center;
      align-items: center;

      ::v-deep .el-input__inner {
        border-radius: 10px !important;
        background-color: #F8F8F8;
      }

      .add-btn {
        padding: 5px !important;
        margin: 8px;
        font-size: 20px;
        color: #587FF0;
        border: #587FF0 1px solid;
        background-color: #F0F8FF;
        border-radius: 50%;
      }

    }

    .chat-list-loading {
      height: 50px;
      background-color: #eee;

      .chat-loading-box {
        height: 100%;
      }
    }

    .chat-list-items {
      flex: 1;
      background: #F8F8F8;
      margin: 0 3px;
    }
  }
}

::v-deep.el-scrollbar__bar .is-horizontal {
  height: 0 !important;
}

.chat-box {
  position: relative;
  width: 100%;
  background: #fff;
}
</style>